package wpp.fxservice;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import wpp.util.IOUtil;
import javafx.concurrent.Service;
import javafx.concurrent.Task;

public class DownloadFileService extends Service<Integer> {
	
	private static final Integer ASSUMPTIVE_FILE_SIZE = 1000000;
	
	private String fileURLPath;
	private File localFile;
	private Boolean override;
	
	public DownloadFileService(String url, File localFile, Boolean override) {
		this.fileURLPath = url;
		this.localFile = localFile;
		this.override = override;
	}
	
	@Override
	protected Task<Integer> createTask() {
		return new Task<Integer>() {
			@Override
			protected Integer call() throws Exception {
				if(!override && localFile.exists()) {
					return Integer.MAX_VALUE;
				}
				InputStream in = null;
				OutputStream out = null;
				Integer readed = 0;
				try {
					IOUtil.createFileIfNotExists(localFile);
					in = new BufferedInputStream(new URL(fileURLPath).openStream());
					out = new BufferedOutputStream(new FileOutputStream(localFile));					
					int c = 0;					
					byte[] bs = new byte[1024 * 1024];
					while(( c = in.read(bs)) != -1) {
						readed += c;
						updateProgress(readed, readed >= ASSUMPTIVE_FILE_SIZE ? readed + 100 : ASSUMPTIVE_FILE_SIZE);
						out.write(bs, 0, c);
					}	
					out.flush();	
					updateProgress(1, 1);
				} finally {
					if(in != null) {
						in.close();
					}
					if(out != null) {
						out.close();
					}
				}
				return readed;
			}
		};
	}
}
